package com.zhao.utils

import com.zhao.common.Constant
import redis.clients.jedis
import redis.clients.jedis.{HostAndPort, JedisCluster, JedisPoolConfig}

import java.util

/**
 * Description: JedisCluster工具类<br/>
 * Copyright (c) ，2021 ， 赵 <br/>
 * A wet person does not fear the rain. <br/>
 * Date： 2021/1/12 15:42
 *
 * @author 柒柒
 * @version : 1.0
 */

object JedisClusterUtils {

  private val hostAndPorts: String = CommonUtil.load.getString(Constant.REDIS_HOST_PORT)

  //准备JedisCluster池,并进行实例的填充
  val pool: util.LinkedList[JedisCluster] = new util.LinkedList

  for (i <- 1 to 100) {
    pool.add(createJedisJedisCluster)
  }

  /**
   * 获得JdisCluster的实例
   * @return
   */
  def createJedisJedisCluster = {
    val timeOut = CommonUtil.load.getInt(Constant.MAX_WAIT_MILLIS)

    val nodes: util.HashSet[HostAndPort] = new util.HashSet[HostAndPort]

    val poolConfig = new JedisPoolConfig
    poolConfig.setMaxTotal(CommonUtil.load.getInt(Constant.MAX_TOTAL))
    poolConfig.setMaxIdle(CommonUtil.load.getInt(Constant.MAX_IDLE))
    poolConfig.setMaxWaitMillis(CommonUtil.load.getInt(Constant.MAX_WAIT_MILLIS))
    poolConfig.setTestOnBorrow(CommonUtil.load.getBoolean(Constant.TEST_ON_BORROW))

//    nodes.add(new HostAndPort("192.168.18.101",7001))
//    nodes.add(new HostAndPort("192.168.18.101",7002))
//    nodes.add(new HostAndPort("192.168.18.102",7003))
//    nodes.add(new HostAndPort("192.168.18.102",7004))
//    nodes.add(new HostAndPort("192.168.18.103",7005))
//    nodes.add(new HostAndPort("192.168.18.103",7006))

    val hosts: Array[String] = hostAndPorts.split("#")

    for (hostPort <- hosts) {
      val ipport: Array[String] = hostPort.split(":")
      val ip: String = ipport(0)
      val port: Int = ipport(1).toInt
      nodes.add(new HostAndPort(ip, port))
    }

    new JedisCluster(nodes,timeOut,timeOut,poolConfig)
  }

  /**
   * 从池中取出一个JedisCluster的实例
   * @return
   */
  def getJedisCluster = {
    if (pool.size > 0) {
      AnyRef.synchronized({
        while (pool.size == 0) {
          CommonUtil.sleep(1)
        }
        pool.poll()
      })
    }else {
      pool.poll()
    }
  }

  /**
   * 释放资源(本质:将JedisCluster的实例置于pool中,供别的线程使用)
   * @param cluster
   */
  def releaseResource(cluster: JedisCluster) = {
    if (cluster != null) {
      pool.push(cluster)
    }
  }
}



















